"""
FileName：order_db_validator.py
Description：
Author：gaojiahui
Time：2025/8/15 16:48
Website：https://gitee.com/gao-jiahui
"""
from numpy.ma.core import resize

from utils.database_manager import DatabaseManager, logger


class OrderDBValidator(DatabaseManager):
    ORDER_TABLE = "pig_order"
    ORDER_ITEM_TABLE = "pig_order_item"
    PRODUCT_TABLE = "pig_product"
    LOG_TABLE = "pig_order_log"

    def get_order_by_id(self, order_id):
        """获取订单主表信息"""
        return self.execute_query(
            f"SELECT * FROM {self.ORDER_TABLE} WHERE order_id = %s",
            (order_id,)
        )[0]

    def get_order_items(self, order_id):
        """获取订单明细"""
        return self.execute_query(
            f"SELECT * FROM {self.ORDER_ITEM_TABLE} WHERE order_id = %",
            (order_id,)
        )

    def get_product_stock(self, product_id):
        """获取商品当前库存"""
        result = self.execute_query(
            f"SELECT stock FROM {self.PRODUCT_TABLE} WHERE product_id = %s",
            (product_id,)
        )
        return result[0]["stock"] if result else None

    def get_order_logs(self, order_id,action_type):
        """获取订单操作日志"""
        return self.execute_query(
            f"SELECT * FROM {self.LOG_TABLE} WHERE  order_id = %s AND action = %s",
            (order_id,action_type)
        )

    # 在validate_order_creation中添加异常处理
    def validate_order_creation(self, order_data, api_response):
        """
        验证订单创建数据一致性
        :param order_data: 接口请求数据
        :param api_response: 接口响应数据
        :return: 校验结果字典
        """

        try:
            order_id = api_response["data"]["order_id"]
            result = {"passed": True, "details": []}

            # 1. 验证订单主表
            db_order = self.get_order_by_id(order_id)
            self._compare_values(
                result,
                "订单金额",
                float(api_response["data"]["total_amount"]),
                float(db_order["total_amount"]),
                tolerance=0.01
            )

            # 2. 验证订单明细
            db_items = self.get_order_items(order_id)
            api_items = order_data["products"]

            if len(db_items) != len(api_items):
                result["passed"] = False
                result["details"].append(f"明细数量不匹配:DB={len(db_items)} vs API={len(api_items)}")

            for api_item in api_items:
                db_item = next((item for item in db_items if item["product_id"] == api_item["product_id"]), None)
                if not db_item:
                    result["passed"] = False
                    result["details"].append(f"商品{api_item['product_id']}在数据库中不存在")
                    continue

                self._compare_values(
                    result,
                    f"商品{api_item['product_id']}数量",
                    api_item["quantity"],
                    db_item["quantity"]
                )

                # 3. 验证库存扣减
                original_stock = self.get_product_stock(api_item["product_id"])
                if original_stock is None:
                    result["passed"] = False
                    result["details"].append(f"商品{api_item['product_id']}库存记录不存在")
                    continue

                expected_stock = original_stock - api_item["quantity"]
                current_stock = self.get_product_stock(api_item["product_id"])

                self._compare_values(
                    result,
                    f"商品{api_item['product_id']}库存",
                    expected_stock,
                    current_stock
                )
            # 4.验证操作日志
            logs = self.get_order_logs(order_id,"CREATE")
            if not logs:
                result["passed"] = False
                result["details"].append("缺少创建日志记录")
            else:
                self._compare_values(
                    result,
                    "操作人",
                    order_data["user_id"],
                    logs[0]["operator_id"]
                )
            return result
        except Exception as e:
            logger.exception("数据库校验异常")
            return {
                "passed": False,
                "details": [f"校验过程异常:{str(e)}"]
            }

    @staticmethod
    def _compare_values(result,field,expected,actual,tolerance=0):
        """比较值并记录结果"""
        if isinstance(expected,float) and isinstance(actual,float):
            passed = abs(expected - actual) <= tolerance
        else:
            passed = expected == actual

        if not passed:
            result["passed"] = False
            result["details"].append(
                f"{field}不匹配:预期={expected},实际={actual}" +
                (f" (容差±{tolerance})" if tolerance else "")
            )

    # 批量查询优化
    def get_multiple_product_stocks(self,product_ids):
        """批量获取商品库存"""
        if not product_ids:
            return {}

        placeholders = ','.join(['%s'] * len(product_ids))
        results = self.execute_query(
            f"SELECT product_id, stock FROM pig_product WHERE product_id IN ({placeholders})",
            tuple(product_ids)
        )

        return {r["product_id"]: r["stock"] for r in results}

    # 高级校验逻辑
    def validate_data_with_rules(self,entity_id,rules):
        """基于规则执行校验"""
        results = []
        for rule in rules:
            table = rule["table"]
            # 查询数据库数据
            db_data = self.execute_query(
                f"SELECT * FROM {table} WHERE {rule.get('key_filed','id')} = %s",
                (entity_id,)
            )[0]

            for field,config in rule["fields"].item():
                actual = db_data.get(field)

                if config["compare"] == "exact":
                    expected = config.get("expected",actual)
                    passed = actual == expected
                elif config["compare"] == "float":
                    tolerance = config.get("tolerance", 0.001)
                    expected = float(config.get("expected",actual))
                    passed = abs(actual - expected) <= tolerance
                # 其他类型比较

                results.append({
                    "table": table,
                    "field": field,
                    "passed": passed,
                    "expected": expected,
                    "actual": actual
                })
        return results

    # 扩展日志校验
    def validate_order_log(self,order_id,expected_action,expected_operator):
        """验证订单操作日志"""
        logs = self.get_order_logs(order_id,expected_action)
        assert len(logs) > 0, f"缺少{expected_action}日志"
        assert logs[0]["operator_id"] == expected_operator

    # 实现退款校验
    def validate_order_refund(self,order_id,refund_amount):
        """验证订单退款数据"""
        order = self.get_order_by_id(order_id)
        assert order["status"] == "REFUNDED"
        assert abs(order["refund_amount"] - refund_amount) <= 0.01

        # 验证资金流水
        transactions = self.execute_query(
            "SELECT * FROM pig_transaction WHERE order_id = %s AND type = 'REFUND'",
            (order_id,)
        )
        assert len(transactions) == 1